<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="浏览器的渲染过程">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2021-05-10-browser-rendering-process/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="og:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/browser-rendering-process/05.png">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/browser-rendering-process/04.png">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/browser-rendering-process/03.png">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/browser-rendering-process/02.png">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/browser-rendering-process/01.png">
  <meta property="article:published_time" content="2021-05-10T02:27:25.000Z">
  <meta property="article:modified_time" content="2021-05-10T02:27:25.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="FrontEnd">
  <meta property="article:tag" content="渲染">
  <meta property="article:tag" content="回流">
  <meta property="article:tag" content="重排">
  <meta property="article:tag" content="重绘">
  <meta name="twitter:card" content="summary">
  <meta name="twitter:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2021-05-10-browser-rendering-process/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>浏览器的渲染过程 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E7%9A%84%E6%B8%B2%E6%9F%93%E8%BF%87%E7%A8%8B"><span class="nav-number">1.</span> <span class="nav-text">浏览器的渲染过程</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%94%9F%E6%88%90%E6%B8%B2%E6%9F%93%E6%A0%91"><span class="nav-number">1.1.</span> <span class="nav-text">生成渲染树</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9B%9E%E6%B5%81"><span class="nav-number">1.2.</span> <span class="nav-text">回流</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%87%8D%E7%BB%98"><span class="nav-number">1.3.</span> <span class="nav-text">重绘</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%95%E6%97%B6%E5%8F%91%E7%94%9F%E5%9B%9E%E6%B5%81%E5%92%8C%E9%87%8D%E7%BB%98"><span class="nav-number">2.</span> <span class="nav-text">何时发生回流和重绘</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E7%9A%84%E4%BC%98%E5%8C%96%E6%9C%BA%E5%88%B6"><span class="nav-number">3.</span> <span class="nav-text">浏览器的优化机制</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%87%8F%E5%B0%91%E5%9B%9E%E6%B5%81%E5%92%8C%E9%87%8D%E7%BB%98"><span class="nav-number">4.</span> <span class="nav-text">减少回流和重绘</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9C%80%E5%B0%8F%E5%8C%96%E5%9B%9E%E6%B5%81%E5%92%8C%E9%87%8D%E7%BB%98"><span class="nav-number">4.1.</span> <span class="nav-text">最小化回流和重绘</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%90%88%E5%B9%B6CSS%E4%BF%AE%E6%94%B9"><span class="nav-number">4.2.</span> <span class="nav-text">合并CSS修改</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%89%B9%E9%87%8F%E4%BF%AE%E6%94%B9DOM"><span class="nav-number">4.3.</span> <span class="nav-text">批量修改DOM</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%81%BF%E5%85%8D%E8%A7%A6%E5%8F%91%E5%90%8C%E6%AD%A5%E5%B8%83%E5%B1%80%E4%BA%8B%E4%BB%B6"><span class="nav-number">4.4.</span> <span class="nav-text">避免触发同步布局事件</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AF%B9%E4%BA%8E%E5%A4%8D%E6%9D%82%E5%8A%A8%E7%94%BB%E6%95%88%E6%9E%9C-%E4%BD%BF%E7%94%A8%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D%E8%AE%A9%E5%85%B6%E8%84%B1%E7%A6%BB%E6%96%87%E6%A1%A3%E6%B5%81"><span class="nav-number">4.5.</span> <span class="nav-text">对于复杂动画效果,使用绝对定位让其脱离文档流</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#css3%E7%A1%AC%E4%BB%B6%E5%8A%A0%E9%80%9F%EF%BC%88GPU%E5%8A%A0%E9%80%9F%EF%BC%89"><span class="nav-number">4.6.</span> <span class="nav-text">css3硬件加速（GPU加速）</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">5.</span> <span class="nav-text">总结</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E6%96%87%E7%8C%AE"><span class="nav-number">6.</span> <span class="nav-text">参考文献</span></a></li>
                </ol>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2021-05-10-browser-rendering-process/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              浏览器的渲染过程
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2021-05-10 10:27:25" itemprop="dateCreated datePublished" datetime="2021-05-10T10:27:25+08:00">2021-05-10</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/FrontEnd/" itemprop="url" rel="index"><span itemprop="name">FrontEnd</span></a>
                  </span>
                </span>


                <span id="/blob/2021-05-10-browser-rendering-process/" class="post-meta-item leancloud_visitors" data-flag-title="浏览器的渲染过程" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <p><a target="_blank" rel="noopener" href="https://github.com/jwenjian/visitor-count-badge"><img src="" data-original="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io" alt="总访客数量"></a></p>
            <p>回流和重绘可以说是每一个web开发者都经常听到的两个词语，我也不例外，可是我之前一直不是很清楚这两步具体做了什么事情。最近由于部门内部要做分享，所以对其进行了一些研究，看了一些博客和书籍，整理了一些内容并且结合一些例子，写了这篇文章，希望可以帮助到大家。</p>
            <blockquote>
              <p>网上有回流和重排两个说法，其实都是一个意思</p>
            </blockquote>
            <h2 id="浏览器的渲染过程"><a href="#浏览器的渲染过程" class="headerlink" title="浏览器的渲染过程"></a>浏览器的渲染过程</h2>
            <p>本文先从浏览器的渲染过程来从头到尾的讲解一下回流重绘，如果大家想直接看如何减少回流和重绘，可以跳到后面。（这个渲染过程来自<a target="_blank" rel="noopener" href="https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-tree-construction?hl=zh-cn">MDN</a>）</p>
            <p><a target="_blank" rel="noopener" href="https://camo.githubusercontent.com/97293716a8b6dd2fcfc4ae5364e37f8f55affaa4/68747470733a2f2f757365722d676f6c642d63646e2e786974752e696f2f323031382f392f332f313635396462313465373733663963633f773d36323426683d32383926663d706e6726733d3431303537"><img src="" data-original="/images/FrontEnd/browser-rendering-process/05.png" alt="webkit渲染过程"></a></p>
            <p>从上面这个图上，我们可以看到，浏览器渲染过程如下：</p>
            <ol>
              <li>解析HTML，生成DOM树，解析CSS，生成CSSOM树</li>
              <li>将DOM树和CSSOM树结合，生成渲染树(Render Tree)</li>
              <li>Layout(回流):根据生成的渲染树，进行回流(Layout)，得到节点的几何信息（位置，大小）</li>
              <li>Painting(重绘):根据渲染树以及回流得到的几何信息，得到节点的绝对像素</li>
              <li>Display:将像素发送给GPU，展示在页面上。（这一步其实还有很多内容，比如会在GPU将多个合成层合并为同一个层，并展示在页面中。而css3硬件加速的原理则是新建合成层，这里我们不展开，之后有机会会写一篇博客）</li>
            </ol>
            <p>渲染过程看起来很简单，让我们来具体了解下每一步具体做了什么。</p>
            <h3 id="生成渲染树"><a href="#生成渲染树" class="headerlink" title="生成渲染树"></a>生成渲染树</h3>
            <p><a target="_blank" rel="noopener" href="https://camo.githubusercontent.com/418de75913c2f669814165541d2ad87ee9c347b277408a3bf79d442d2e951650/68747470733a2f2f696d67323031382e636e626c6f67732e636f6d2f626c6f672f3939333334332f3230313831322f3939333334332d32303138313231303233313235303632302d313730393936343332302e706e67"><img src="" data-original="/images/FrontEnd/browser-rendering-process/04.png" alt="生成渲染树"></a></p>
            <p>为了构建渲染树，浏览器主要完成了以下工作：</p>
            <ol>
              <li>从DOM树的根节点开始遍历每个可见节点。</li>
              <li>对于每个可见的节点，找到CSSOM树中对应的规则，并应用它们。</li>
              <li>根据每个可见节点以及其对应的样式，组合生成渲染树。</li>
            </ol>
            <p>第一步中，既然说到了要遍历可见的节点，那么我们得先知道，什么节点是不可见的。不可见的节点包括：</p>
            <ul>
              <li>一些不会渲染输出的节点，比如script、meta、link等。</li>
              <li>一些通过css进行隐藏的节点。比如display:none。注意，利用visibility和opacity隐藏的节点，还是会显示在渲染树上的。只有display:none的节点才不会显示在渲染树上。</li>
            </ul>
            <p><strong>注意：渲染树只包含可见的节点</strong></p>
            <h3 id="回流"><a href="#回流" class="headerlink" title="回流"></a>回流</h3>
            <p>前面我们通过构造渲染树，我们将可见DOM节点以及它对应的样式结合起来，可是我们还需要计算它们在设备视口(viewport)内的确切位置和大小，这个计算的阶段就是回流。</p>
            <p>为了弄清每个对象在网站上的确切大小和位置，浏览器从渲染树的根节点开始遍历，我们可以以下面这个实例来表示：</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">  &lt;head&gt;</span><br><span class="line">    &lt;meta name&#x3D;&quot;viewport&quot; content&#x3D;&quot;width&#x3D;device-width,initial-scale&#x3D;1&quot;&gt;</span><br><span class="line">    &lt;title&gt;Critial Path: Hello world!&lt;&#x2F;title&gt;</span><br><span class="line">  &lt;&#x2F;head&gt;</span><br><span class="line">  &lt;body&gt;</span><br><span class="line">    &lt;div style&#x3D;&quot;width: 50%&quot;&gt;</span><br><span class="line">      &lt;div style&#x3D;&quot;width: 50%&quot;&gt;Hello world!&lt;&#x2F;div&gt;</span><br><span class="line">    &lt;&#x2F;div&gt;</span><br><span class="line">  &lt;&#x2F;body&gt;</span><br><span class="line">&lt;&#x2F;html&gt;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>我们可以看到，第一个div将节点的显示尺寸设置为视口宽度的50%，第二个div将其尺寸设置为父节点的50%。而在回流这个阶段，我们就需要根据视口具体的宽度，将其转为实际的像素值。（如下图）</p>
            <p><a target="_blank" rel="noopener" href="https://camo.githubusercontent.com/9921dc3c939e141611449fd74bfdb535a409ab361c4086427d9874c5b95cdc8b/68747470733a2f2f696d67323031382e636e626c6f67732e636f6d2f626c6f672f3939333334332f3230313831322f3939333334332d32303138313231303233313233323630352d3838393430353032342e706e67"><img src="" data-original="/images/FrontEnd/browser-rendering-process/03.png" alt="img"></a></p>
            <h3 id="重绘"><a href="#重绘" class="headerlink" title="重绘"></a>重绘</h3>
            <p>最终，我们通过构造渲染树和回流阶段，我们知道了哪些节点是可见的，以及可见节点的样式和具体的几何信息(位置、大小)，那么我们就可以将渲染树的每个节点都转换为屏幕上的实际像素，这个阶段就叫做重绘节点。</p>
            <p>既然知道了浏览器的渲染过程后，我们就来探讨下，何时会发生回流和重绘。</p>
            <h2 id="何时发生回流和重绘"><a href="#何时发生回流和重绘" class="headerlink" title="何时发生回流和重绘"></a>何时发生回流和重绘</h2>
            <p>我们前面知道了，回流这一阶段主要是计算节点的位置和几何信息，那么当页面布局和几何信息发生变化的时候，就需要回流。比如以下情况：</p>
            <ul>
              <li>添加或删除可见的DOM元素</li>
              <li>元素的位置发生变化</li>
              <li>元素的尺寸发生变化（包括外边距、内边框、边框大小、高度和宽度等）</li>
              <li>内容发生变化，比如文本变化或图片被另一个不同尺寸的图片所替代。</li>
              <li>页面一开始渲染的时候（这肯定避免不了）</li>
              <li>浏览器的窗口尺寸变化（因为回流是根据视口的大小来计算元素的位置和大小的）</li>
            </ul>
            <p><strong>注意：回流一定会触发重绘，而重绘不一定会回流</strong></p>
            <p>根据改变的范围和程度，渲染树中或大或小的部分需要重新计算，有些改变会触发整个页面的回流，比如，滚动条出现的时候或者修改了根节点。</p>
            <p>重绘：是在一个元素的外观被改变所触发的浏览器行为，浏览器会根据元素的新属性重新绘制，使元素呈现新的外观。</p>
            <h2 id="浏览器的优化机制"><a href="#浏览器的优化机制" class="headerlink" title="浏览器的优化机制"></a>浏览器的优化机制</h2>
            <p>现代的浏览器都是很聪明的，由于每次重排都会造成额外的计算消耗，因此大多数浏览器都会通过队列化修改并批量执行来优化回流过程。浏览器会将修改操作放入到队列里，直到过了一段时间或者操作达到了一个阈值，才清空队列。但是！<strong>当你获取布局信息的操作的时候，会强制队列刷新</strong>，比如当你访问以下属性或者使用以下方法：</p>
            <ul>
              <li>offsetTop、offsetLeft、offsetWidth、offsetHeight</li>
              <li>scrollTop、scrollLeft、scrollWidth、scrollHeight</li>
              <li>clientTop、clientLeft、clientWidth、clientHeight</li>
              <li>getComputedStyle()</li>
              <li>getBoundingClientRect</li>
              <li>具体可以访问这个网站：<a target="_blank" rel="noopener" href="https://gist.github.com/paulirish/5d52fb081b3570c81e3a">https://gist.github.com/paulirish/5d52fb081b3570c81e3a</a></li>
            </ul>
            <p>以上属性和方法都需要返回最新的布局信息，因此浏览器不得不清空队列，触发回流重绘来返回正确的值。因此，我们在修改样式的时候，<strong>最好避免使用上面列出的属性，他们都会刷新渲染队列。</strong>如果要使用它们，最好将值缓存起来。</p>
            <h2 id="减少回流和重绘"><a href="#减少回流和重绘" class="headerlink" title="减少回流和重绘"></a>减少回流和重绘</h2>
            <p>好了，到了我们今天的重头戏，前面说了这么多背景和理论知识，接下来让我们谈谈如何减少回流和重绘。</p>
            <h3 id="最小化回流和重绘"><a href="#最小化回流和重绘" class="headerlink" title="最小化回流和重绘"></a>最小化回流和重绘</h3>
            <p>由于回流和重绘可能代价比较昂贵，因此最好就是可以减少它的发生次数。</p>
            <h3 id="合并CSS修改"><a href="#合并CSS修改" class="headerlink" title="合并CSS修改"></a>合并CSS修改</h3>
            <p>为了减少发生次数，我们可以合并多次对DOM和样式的修改，然后一次处理掉。考虑这个例子</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">const el &#x3D; document.getElementById(&#39;test&#39;);</span><br><span class="line">el.style.padding &#x3D; &#39;5px&#39;;</span><br><span class="line">el.style.borderLeft &#x3D; &#39;1px&#39;;</span><br><span class="line">el.style.borderRight &#x3D; &#39;2px&#39;;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>例子中，有三个样式属性被修改了，每一个都会影响元素的几何结构，引起回流。当然，大部分现代浏览器都对其做了优化，因此，只会触发一次回流。但是如果在旧版的浏览器或者在上面代码执行的时候，有其他代码访问了布局信息(上文中的会触发回流的布局信息)，那么就会导致三次回流。</p>
            <p>因此，我们可以合并所有的改变然后依次处理，比如我们可以采取以下的方式：</p>
            <ul>
              <li>
                <p>使用cssText</p>
                <figure class="highlight plain">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">const el &#x3D; document.getElementById(&#39;test&#39;);</span><br><span class="line">el.style.cssText +&#x3D; &#39;border-left: 1px; border-right: 2px; padding: 5px;&#39;;</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
              </li>
              <li>
                <p>修改CSS的class</p>
                <figure class="highlight plain">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">const el &#x3D; document.getElementById(&#39;test&#39;);</span><br><span class="line">el.className +&#x3D; &#39; active&#39;;</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
              </li>
            </ul>
            <h3 id="批量修改DOM"><a href="#批量修改DOM" class="headerlink" title="批量修改DOM"></a>批量修改DOM</h3>
            <p>当我们需要对DOM对一系列修改的时候，可以通过以下步骤减少回流重绘次数：</p>
            <ol>
              <li>使元素脱离文档流</li>
              <li>对其进行多次修改</li>
              <li>将元素带回到文档中。</li>
            </ol>
            <p>该过程的第一步和第三步可能会引起回流，但是经过第一步之后，对DOM的所有修改都不会引起回流，因为它已经不在渲染树了。</p>
            <p>有三种方式可以让DOM脱离文档流：</p>
            <ul>
              <li>隐藏元素，应用修改，重新显示</li>
              <li>使用文档片段(document fragment)在当前DOM之外构建一个子树，再把它拷贝回文档。</li>
              <li>将原始元素拷贝到一个脱离文档的节点中，修改节点后，再替换原始的元素。</li>
            </ul>
            <p>考虑我们要执行一段批量插入节点的代码：</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">function appendDataToElement(appendToElement, data) &#123;</span><br><span class="line">    let li;</span><br><span class="line">    for (let i &#x3D; 0; i &lt; data.length; i++) &#123;</span><br><span class="line">    	li &#x3D; document.createElement(&#39;li&#39;);</span><br><span class="line">        li.textContent &#x3D; &#39;text&#39;;</span><br><span class="line">        appendToElement.appendChild(li);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">const ul &#x3D; document.getElementById(&#39;list&#39;);</span><br><span class="line">appendDataToElement(ul, data);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>如果我们直接这样执行的话，由于每次循环都会插入一个新的节点，会导致浏览器回流一次。</p>
            <p>我们可以使用这三种方式进行优化:</p>
            <p><strong>隐藏元素，应用修改，重新显示</strong></p>
            <p>这个会在展示和隐藏节点的时候，产生两次重绘</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">function appendDataToElement(appendToElement, data) &#123;</span><br><span class="line">    let li;</span><br><span class="line">    for (let i &#x3D; 0; i &lt; data.length; i++) &#123;</span><br><span class="line">    	li &#x3D; document.createElement(&#39;li&#39;);</span><br><span class="line">        li.textContent &#x3D; &#39;text&#39;;</span><br><span class="line">        appendToElement.appendChild(li);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">const ul &#x3D; document.getElementById(&#39;list&#39;);</span><br><span class="line">ul.style.display &#x3D; &#39;none&#39;;</span><br><span class="line">appendDataToElement(ul, data);</span><br><span class="line">ul.style.display &#x3D; &#39;block&#39;;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><strong>使用文档片段(document fragment)在当前DOM之外构建一个子树，再把它拷贝回文档</strong></p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">const ul &#x3D; document.getElementById(&#39;list&#39;);</span><br><span class="line">const fragment &#x3D; document.createDocumentFragment();</span><br><span class="line">appendDataToElement(fragment, data);</span><br><span class="line">ul.appendChild(fragment);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><strong>将原始元素拷贝到一个脱离文档的节点中，修改节点后，再替换原始的元素。</strong></p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">const ul &#x3D; document.getElementById(&#39;list&#39;);</span><br><span class="line">const clone &#x3D; ul.cloneNode(true);</span><br><span class="line">appendDataToElement(clone, data);</span><br><span class="line">ul.parentNode.replaceChild(clone, ul);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>对于上述那种情况，我写了一个<a target="_blank" rel="noopener" href="https://chenjigeng.github.io/example/share/%E9%81%BF%E5%85%8D%E5%9B%9E%E6%B5%81%E9%87%8D%E7%BB%98/%E6%89%B9%E9%87%8F%E4%BF%AE%E6%94%B9DOM.html">demo</a>来测试修改前和修改后的性能。然而实验结果不是很理想。</p>
            <p><strong>原因：原因其实上面也说过了，浏览器会使用队列来储存多次修改，进行优化，所以对这个优化方案，我们其实不用优先考虑。</strong></p>
            <h3 id="避免触发同步布局事件"><a href="#避免触发同步布局事件" class="headerlink" title="避免触发同步布局事件"></a>避免触发同步布局事件</h3>
            <p>上文我们说过，当我们访问元素的一些属性的时候，会导致浏览器强制清空队列，进行强制同步布局。举个例子，比如说我们想将一个p标签数组的宽度赋值为一个元素的宽度，我们可能写出这样的代码：</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">function initP() &#123;</span><br><span class="line">    for (let i &#x3D; 0; i &lt; paragraphs.length; i++) &#123;</span><br><span class="line">        paragraphs[i].style.width &#x3D; box.offsetWidth + &#39;px&#39;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这段代码看上去是没有什么问题，可是其实会造成很大的性能问题。在每次循环的时候，都读取了box的一个offsetWidth属性值，然后利用它来更新p标签的width属性。这就导致了每一次循环的时候，浏览器都必须先使上一次循环中的样式更新操作生效，才能响应本次循环的样式读取操作。每一次循环都会强制浏览器刷新队列。我们可以优化为:</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">const width &#x3D; box.offsetWidth;</span><br><span class="line">function initP() &#123;</span><br><span class="line">    for (let i &#x3D; 0; i &lt; paragraphs.length; i++) &#123;</span><br><span class="line">        paragraphs[i].style.width &#x3D; width + &#39;px&#39;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>同样，我也写了个<a target="_blank" rel="noopener" href="https://chenjigeng.github.io/example/share/%E9%81%BF%E5%85%8D%E5%9B%9E%E6%B5%81%E9%87%8D%E7%BB%98/%E9%81%BF%E5%85%8D%E5%BF%AB%E9%80%9F%E8%BF%9E%E7%BB%AD%E7%9A%84%E5%B8%83%E5%B1%80.html">demo</a>来比较两者的性能差异。你可以自己点开这个demo体验下。这个对比差距就比较明显。</p>
            <h3 id="对于复杂动画效果-使用绝对定位让其脱离文档流"><a href="#对于复杂动画效果-使用绝对定位让其脱离文档流" class="headerlink" title="对于复杂动画效果,使用绝对定位让其脱离文档流"></a>对于复杂动画效果,使用绝对定位让其脱离文档流</h3>
            <p>对于复杂动画效果，由于会经常的引起回流重绘，因此，我们可以使用绝对定位，让它脱离文档流。否则会引起父元素以及后续元素频繁的回流。这个我们就直接上个<a target="_blank" rel="noopener" href="https://chenjigeng.github.io/example/share/%E9%81%BF%E5%85%8D%E5%9B%9E%E6%B5%81%E9%87%8D%E7%BB%98/%E5%B0%86%E5%A4%8D%E6%9D%82%E5%8A%A8%E7%94%BB%E6%B5%AE%E5%8A%A8%E5%8C%96.html">例子</a>。</p>
            <p>打开这个例子后，我们可以打开控制台，控制台上会输出当前的帧数(虽然不准)。</p>
            <p><a target="_blank" rel="noopener" href="https://camo.githubusercontent.com/11da67764416d03b236302081145ddf331ba8459ca72a2903b9fde7d539bc763/68747470733a2f2f696d67323031382e636e626c6f67732e636f6d2f626c6f672f3939333334332f3230313831322f3939333334332d32303138313231303233313034383630392d3631393032323439342e706e67"><img src="" data-original="/images/FrontEnd/browser-rendering-process/02.png" alt="image-20181210223750055"></a></p>
            <p>从上图中，我们可以看到，帧数一直都没到60。这个时候，只要我们点击一下那个按钮，把这个元素设置为绝对定位，帧数就可以稳定60。</p>
            <h3 id="css3硬件加速（GPU加速）"><a href="#css3硬件加速（GPU加速）" class="headerlink" title="css3硬件加速（GPU加速）"></a>css3硬件加速（GPU加速）</h3>
            <p>比起考虑如何减少回流重绘，我们更期望的是，根本不要回流重绘。这个时候，css3硬件加速就闪亮登场啦！！</p>
            <p><strong>划重点：使用css3硬件加速，可以让transform、opacity、filters这些动画不会引起回流重绘 。但是对于动画的其它属性，比如background-color这些，还是会引起回流重绘的，不过它还是可以提升这些动画的性能。</strong></p>
            <p>本篇文章只讨论如何使用，暂不考虑其原理，之后有空会另外开篇文章说明。</p>
            <h4 id="如何使用"><a href="#如何使用" class="headerlink" title="如何使用"></a>如何使用</h4>
            <p>常见的触发硬件加速的css属性：</p>
            <ul>
              <li>transform</li>
              <li>opacity</li>
              <li>filters</li>
              <li>Will-change</li>
            </ul>
            <h4 id="效果"><a href="#效果" class="headerlink" title="效果"></a>效果</h4>
            <p>我们可以先看个<a target="_blank" rel="noopener" href="https://chenjigeng.github.io/example/share/%E5%AF%B9%E6%AF%94gpu%E5%8A%A0%E9%80%9F/gpu%E5%8A%A0%E9%80%9F-transform.html">例子</a>。我通过使用chrome的Performance捕获了一段时间的回流重绘情况，实际结果如下图：</p>
            <p><a target="_blank" rel="noopener" href="https://camo.githubusercontent.com/bcf476210ead01fd72acc69b599b1f6d25775f35b1219892238be3d6261cf4be/68747470733a2f2f696d67323031382e636e626c6f67732e636f6d2f626c6f672f3939333334332f3230313831322f3939333334332d32303138313231303233303935393938372d313431393334383634342e706e67"><img src="" data-original="/images/FrontEnd/browser-rendering-process/01.png" alt="image-20181210225609533"></a></p>
            <p>从图中我们可以看出，在动画进行的时候，没有发生任何的回流重绘。如果感兴趣你也可以自己做下实验。</p>
            <h4 id="重点"><a href="#重点" class="headerlink" title="重点"></a>重点</h4>
            <ul>
              <li>使用css3硬件加速，可以让transform、opacity、filters这些动画不会引起回流重绘</li>
              <li>对于动画的其它属性，比如background-color这些，还是会引起回流重绘的，不过它还是可以提升这些动画的性能。</li>
            </ul>
            <h4 id="css3硬件加速的坑"><a href="#css3硬件加速的坑" class="headerlink" title="css3硬件加速的坑"></a>css3硬件加速的坑</h4>
            <ul>
              <li>如果你为太多元素使用css3硬件加速，会导致内存占用较大，会有性能问题。</li>
              <li>在GPU渲染字体会导致抗锯齿无效。这是因为GPU和CPU的算法不同。因此如果你不在动画结束的时候关闭硬件加速，会产生字体模糊。</li>
            </ul>
            <h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2>
            <p>本文主要讲了浏览器的渲染过程、浏览器的优化机制以及如何减少甚至避免回流和重绘，希望可以帮助大家更好的理解回流重绘。</p>
            <h2 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h2>
            <ul>
              <li><a target="_blank" rel="noopener" href="https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-tree-construction?hl=zh-cn">渲染树构建、布局及绘制</a></li>
              <li>高性能Javascript</li>
            </ul>

          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/FrontEnd/" rel="tag"># FrontEnd</a>
              <a href="/tags/%E6%B8%B2%E6%9F%93/" rel="tag"># 渲染</a>
              <a href="/tags/%E5%9B%9E%E6%B5%81/" rel="tag"># 回流</a>
              <a href="/tags/%E9%87%8D%E6%8E%92/" rel="tag"># 重排</a>
              <a href="/tags/%E9%87%8D%E7%BB%98/" rel="tag"># 重绘</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2021-04-12-dynamic-setting-of-page-background-color-by-wechat-applet/" rel="prev" title="微信小程序动态设置页面背景色">
                  <i class="fa fa-chevron-left"></i> 微信小程序动态设置页面背景色
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2021-05-17-encryption-scheme-and-implementation-of-front-end-sensitive-data/" rel="next" title="前端敏感数据加密方案及实现">
                  前端敏感数据加密方案及实现 <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>